<?php

namespace api\traits;

use api\common\helpers\Constant;
use api\modules\app\services\CacheService;
use api\modules\manage\services\MenuService;
use Yii;
use yii\web\UnauthorizedHttpException;

trait LoginTrait
{
    public function loginByToken($token, $isLogin = false)
    {
        $identity = Yii::$app->userCenter->loginByTokenNew($token);
        if (empty($identity)) {
            (new CacheService())->removeUserTokenCache($token);
            throw new UnauthorizedHttpException('登录失败，请重新登录');
        }
        if ($isLogin) {
            (new CacheService())->cacheUserInfoByToken($token, $identity);
        }
        return $identity;
    }

    public function loginByTokenNew($token)
    {
        $identity = Yii::$app->userCenter->loginByTokenNew($token);
        (new CacheService())->cacheUserInfoByToken($token, $identity);
    }

    public function loginByUsername($username,$password)
    {
        $identity = Yii::$app->userCenter->loginByUsernameNew($username,$password);
//        $identity = Yii::$app->userCenter->loginByUsername($username,$password);
        if (empty($identity)) {
            throw new UnauthorizedHttpException('登录失败，请重新登录');
        }
        $redis = Yii::$app->redisCache;
        $key = Constant::LOGIN_USER_CACHE_ID . '_' . $identity['id'];
        $res = $redis->set($key, json_encode($identity), 3600 * 6);
        if (empty($res)) {
            throw new \Exception('用户身份缓存失败');
        }
        (new CacheService())->cacheUserInfoByToken($identity['token'], $identity);
        return $identity;
    }

    public function logout($token)
    {
        Yii::$app->userCenter->logout($token);
        (new CacheService())->removeUserTokenCache($token);

        return true;
    }
}